<template>
  <div class="edit-email-form">
    <el-form
      ref="emailForm"
      :model="formData"
      
      :rules="rules"
      label-position="top"
      class="emailForm"
    >
      <el-form-item class="create-item" :label="$t('setting.messageChannel.fields.emailAddress.displayName')" prop="email">
        <el-input v-model="formData.email" :placeholder="$t('setting.messageChannel.fields.emailAddress.placeholder')" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item class="create-item" :label="$t('setting.messageChannel.fields.emailName.displayName')" prop="emailAlias">
        <el-input v-model="formData.emailAlias" :placeholder="$t('setting.messageChannel.fields.emailName.placeholder')" maxlength="10" show-word-limit autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item class="create-item" :label="$t('setting.messageChannel.fields.emailPassword.displayName')" prop="emailPassword">
        <el-input v-model="formData.emailPassword" :placeholder="$t('common.placeholder.input')" autocomplete="off" show-password @input="handPwdChange"></el-input>
      </el-form-item>
      <el-form-item class="create-item" :label="$t('setting.messageChannel.fields.serverSMTP.displayName')" prop="smtpHost">
        <el-input v-model="formData.smtpHost" :placeholder="$t('common.placeholder.input')" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item class="create-item" :label="$t('setting.messageChannel.fields.hostSMTP.displayName')" prop="smtpPort">
        <el-input v-model="formData.smtpPort" :placeholder="$t('setting.messageChannel.fields.hostSMTP.placeholder')" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item class="create-item same-pwd" :label="$t('setting.messageChannel.fields.passwordSMTP.displayName')" prop="smtpCode">
        <el-input v-model="formData.smtpCode" :placeholder="$t('common.placeholder.input')" autocomplete="off" show-password :readonly="checkedPwd" :disabled="checkedPwd"></el-input>
        <el-checkbox v-model="checkedPwd" :label="$t('setting.messageChannel.sameEmailPassword')" size="large" @change="handleCheckedPwd"></el-checkbox>
      </el-form-item>
    </el-form>
    <div class="tip"> 
      <p>{{$t('setting.messageChannel.emailConfigDoc[0]')}}：<span @click="goHelp">{{$t('setting.messageChannel.emailConfigDoc[1]')}}</span></p> 
      <p>{{$t('setting.messageChannel.emailConfigDoc[2]')}}</p> 
    </div>
  </div>
</template>

<script>
import { getRootWindowInitData } from '@src/util/window'
import * as EmailMessageApi from '@src/api/EmailApi';
import { t } from '@src/locales';

export default {
  name: 'email-form',
  props: {
    formStatus: {
      type: Object,
      default: ()=> ({}),
    },
    emailData: {
      type: Object,
      default: ()=> ({}),
    },
  },
  computed:{
    tenantType(){
      return getRootWindowInitData()?.tenantType
    },
  },  
  data() {
    const checkEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error(t('setting.messageChannel.fields.emailAddress.placeholder')));
      } else if (value) {
        let reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
        if (!reg.test(value)) callback(new Error(t('setting.messageChannel.fields.emailAddress.placeholder2')));
      }
      callback();
    };
    const checkEmailAlias = (rule, value, callback) => {
      if (!value) {
        callback(new Error(t('setting.messageChannel.fields.emailName.placeholder2')));
      } else if (value && value.length > 10) {
        callback(new Error(t('common.validate.maxLen', {limit: 10})));
      }
      callback();
    };
    const checkHost = (rule, value, callback) => {
      if (!value) {
        callback(new Error(t('setting.messageChannel.fields.serverSMTP.placeholder')));
      }
      callback();
    };
    const checkPort = (rule, value, callback) => {
      if (!value) {
        callback(new Error(t('setting.messageChannel.fields.hostSMTP.placeholder')));
      }
      callback();
    };
    const checkPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error(t('setting.messageChannel.fields.emailPassword.placeholder')));
      }
      callback();
    };
    const checkSMTPPassword = (rule, value, callback) => {
      if (!value && !this.checkedPwd) {
        callback(new Error(t('setting.messageChannel.fields.passwordSMTP.placeholder')));
      }
      callback();
    };
    return {
      checkedPwd: true,
      rules: {
        email: [
          {
            validator: checkEmail,
            trigger: 'blur',
            required: true,
          },
        ],
        emailAlias: [
          {
            validator: checkEmailAlias,
            trigger: 'blur',
            required: true,
          },
        ],
        emailPassword: [
          {
            validator: checkPassword,
            trigger: 'blur',
            required: true,
          },
        ],
        smtpHost: [
          {
            validator: checkHost,
            trigger: 'blur',
            required: true,
          },
        ],
        smtpPort: [
          {
            validator: checkPort,
            trigger: 'blur',
            required: true,
          },
        ],
        smtpCode: [
          {
            validator: checkSMTPPassword,
            trigger: 'blur',
            required: true,
          },
        ],
      },
      formData: this.emailData.email ? this.emailData : {
        email: '',
        emailAlias: '',
        emailPassword: '',
        smtpHost: '',
        smtpPort: '',
        smtpCode: '',
        isEdit: false
      },
      fromType: this.formStatus,
    };
  },
  watch: {
    formStatus: {
      immediate: true,
      deep: true,
      handler (val) {
        // console.log('watch formStatus', val);
        const { sendTestEmail, submitFrom } = val;
        if (sendTestEmail) {
          this.sendFrom();
        }
        if (submitFrom) {
          this.submit();
        }
      },
    },
    'emailData.isEdit': {
      immediate: true,
      handler(newValue) {
        // console.log('watch isEdit', newValue);
        if(newValue) {
          const { emailPassword, smtpCode } = this.emailData;
          if(emailPassword != smtpCode) {
            this.checkedPwd = false;
          }
        }
      }
    }
  },
  methods: {
    changeFormStatus(name, type) {
      this.fromType[name] = type;
      this.$emit('changeFormStatus', this.fromType);
    },
    // 监听邮箱密码
    handPwdChange(e){
      if(this.checkedPwd) {
        this.formData.smtpCode = e;
      }
    },
    // 切换是否同邮箱密码
    handleCheckedPwd(e){
      if(e && this.formData.emailPassword) {
        this.formData.smtpCode = this.formData.emailPassword;
      }
    },
    // 配置参考文档
    goHelp(){
      let url = ''
      if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcnmNonkcqrzCKHVeKPQXWv9e'
      } else {
        url = 'https://doc.shb.ltd/shb_aa2eox/gdboz9frgdlynqgx/yabn7zqbf12sg8c2/nzv2c1i8ixw103yo.html'
      }
      this.$platform.openLink(url);
    },
    // 编辑配置
    async submit() {
      try {
        const checked = await this.checkForm(this.formData);
        if (!checked) return;
        const { code, message } = await EmailMessageApi.submit(this.formData);
        if (code != 0) return this.$message.warning(message);
        this.changeFormStatus('submitFrom', true);
        this.changeFormStatus('sendTestEmail', false);
        this.$message({
          message: t('common.base.saveSuccess'),
          type: 'success',
          duration: 1500
        });
        setTimeout(() => {
          this.changeFormStatus('editFrom', false);
        }, 100);
      } catch (error) {
        this.changeFormStatus('submitFrom', false);
        console.warn(error);
      }
    },
    // 邮件发送测试
    async testSend(params) {
      try {
        const { code, message } = await EmailMessageApi.testSend(params);
        if (code != 0) return this.$message.warning(message);
        this.$confirm(t('setting.messageChannel.tip.sendTestEmail'), t('common.base.toast'), {
          confirmButtonText: t('common.base.confirm'),
          cancelButtonText: t('common.base.cancel'),
          customClass: 'email-el-message-box'
        })
          .catch(() => {
            this.changeFormStatus('sendTestEmail', false);
          });
      } catch (error) {
        console.warn(error);
      }
    },
    // 表格校验
    checkForm() {
      return new Promise((resolve, reject) => {
        try {
          this.$refs['emailForm'].validate(async valid => {
            if (!valid) {
              this.changeFormStatus('sendTestEmail', false);
              this.changeFormStatus('submitFrom', false);
              resolve(false)
            } else {
              resolve(true)
            }
          });
        } catch (error) {
          resolve(false)
        }
      })
    },
    // 发送测试邮件
    async sendFrom() {
      const checked = await this.checkForm(this.formData);
      if (!checked) return;
      this.$prompt(`${t('setting.messageChannel.inbox')}:`, t('setting.messageChannel.testSend'), {
        confirmButtonText: t('common.base.send'),
        cancelButtonText: t('common.base.close'),
        inputPattern:
					/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
        inputErrorMessage: t('setting.messageChannel.fields.emailAddress.placeholder2'),
        inputPlaceholder: t('setting.messageChannel.fields.emailAddress.placeholder3'),
        customClass: 'email-el-message-box'
      })
        .then(data => {
          if (data.value) {
            this.changeFormStatus('sendTestEmail', false);
            this.formData.receiver = data.value;
            this.testSend(this.formData);
          }
        })
        .catch(() => {
          this.changeFormStatus('sendTestEmail', false);
        });
    },
  },
};
</script>

<style lang="scss">
.edit-email-form {
	.emailForm {
		width: 100%;
		.el-dialog__body {
      padding: 20px 20px 10px;
		}
		.el-form-item {
			margin-bottom: 16px;
		}
		.same-pwd {
			.el-form-item__content {
				display: flex;
				.el-checkbox{
					margin-left: 8px;
				}
			}
		}
		.el-input__inner {
			height: 32px;
			line-height: 32px;
			font-size: 12px;
		}
	}
	.tip {
		color: #faae14;
		margin-top: 20px;
		p:last-child {
			margin-bottom: 0;
		}
		span {
			color: $color-primary;
			cursor: pointer;
		}
	}
}
</style>
